package map.android.baidu.carpool.page.home;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.api2.ComAPIManager;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.baidu.platform.comapi.map.MapUtils;
import com.baidu.platform.comapi.map.config.Preferences;
import map.android.baidu.carpool.CarpoolEntity;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.MainConfigData;
import map.android.baidu.carpool.data.impl.MainInfoData;
import map.android.baidu.carpool.data.impl.UserCenterData;
import map.android.baidu.carpool.model.CarpoolPosition;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.MainInfoResponse;
import map.android.baidu.carpool.response.UserCenterResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.SafeUtils;

import java.util.ArrayList;

/**
 * Created by zhangtongyu on 15/3/30.
 * 嵌入基线的View
 */
public class EntranceInCar{

    private static String TAG = "";

    private RelativeLayout mView;

    private TextView mTextInCarTv;
    private TextView mSubHeadTv;
    private ViewGroup parentView;

    /**只取本地存储的response 本次网络请求将缓存*/
    private MainConfigResponse mainConfigResponse;
    private IDataStatusChangedListener<MainConfigResponse> mMainConfigResponseListener = new IDataStatusChangedListener<MainConfigResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<MainConfigResponse> data, MainConfigResponse response, int dataStatus) {
            if(response != null && response.data != null){
                if(response.data.citylist != null && response.data.carType != null && response.data.customerServicePhone != null) {
                    CarpoolSharedPreferences.setCacheMainConfigResponse(APIProxy.res().getBaseActivity(), response);
                }
            } else {
            }
        }
    };
    /**入口所需显示的数据，缓存在本地  用车入口的留着到后来使用附近车辆或者同行人*/
    private MainInfoResponse mainInfoResponse;
    private IDataStatusChangedListener<MainInfoResponse> mainInfoResponseListener = new IDataStatusChangedListener<MainInfoResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<MainInfoResponse> data, MainInfoResponse response, int dataStatus) {
            if(response != null && response.data != null&& response.errorNo == 0){
                if(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()) == null){
                    //第一次进入 等待网络请求再渲染 并存储
                    updateUI(response);
                }
                CarpoolSharedPreferences.setCacheMainInfoResponse(APIProxy.res().getBaseActivity(), response);
            } else {
                parentView.setVisibility(View.GONE);
            }
        }
    };

    private IDataStatusChangedListener<UserCenterResponse> userCenterResponseListener = new IDataStatusChangedListener<UserCenterResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<UserCenterResponse> data, UserCenterResponse response, int dataStatus) {
            if (response != null && response.data != null && !TextUtils.isEmpty(response.data.unFinishedOrderNum)) {
                if(SafeUtils.safeString2int(response.data.unFinishedOrderNum) != 0){
                    mTextInCarTv.setVisibility(View.VISIBLE);
                    setUnFinishOrderCount(SafeUtils.safeString2int(response.data.unFinishedOrderNum));
                } else {
                    mTextInCarTv.setVisibility(View.GONE);
                }
            } else {
                mTextInCarTv.setVisibility(View.GONE);
            }
        }
    };


    public EntranceInCar(Context context, ViewGroup parent) {
        saveHomeAndCompanyGeo();
        parentView = parent;
        LayoutInflater inflater = APIProxy.res().getInflater();
        mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity());
        mView = (RelativeLayout) inflater.inflate(R.layout.entrance_for_car , parent , false);
        parentView.setVisibility(View.GONE);
        initView();
        loadData();
        if(isSupportCarpool()){
            parentView.setVisibility(View.VISIBLE);
        } else {
            parentView.setVisibility(View.GONE);
            return;
        }
        if(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()) != null){
            //非第一次进入 拿上一次的结果
            updateUI(CarpoolSharedPreferences.getCacheMainInfoResponse(APIProxy.res().getBaseActivity()));
        }
        parentView.addView(mView);
    }

    private void loadData() {
        MainConfigData mainConfigData = new MainConfigData(APIProxy.res().getBaseActivity());
        if(mainConfigResponse != null && mainConfigResponse.data != null){
            mainConfigData.setCache(mainConfigResponse.data.cache);
        }
        mainConfigData.setCityCode(UserInfoSetting.getCityId());
        mainConfigData.get(mMainConfigResponseListener);

        MainInfoData mainInfoData = new MainInfoData(APIProxy.res().getBaseActivity());
        mainInfoData.setStartPlaceInfo(mHomeInfoMoc);
        mainInfoData.setArrivePlaceInfo(mCompanyInfoMoc);
        mainInfoData.post(mainInfoResponseListener);


        UserCenterData userCenterData = new UserCenterData(APIProxy.res().getBaseActivity());
        userCenterData.post(userCenterResponseListener);
    }

    private void updateUI(MainInfoResponse mainInfoResponse) {
        if(mainInfoResponse == null){
            parentView.setVisibility(View.GONE);
            return;
        }
        if(mainInfoResponse.data != null){
            parentView.setVisibility(View.VISIBLE);
            if(!TextUtils.isEmpty(mainInfoResponse.data.carTitle)) {
                mSubHeadTv.setText(mainInfoResponse.data.carTitle);
            }
        } else {
            parentView.setVisibility(View.GONE);
        }

    }


    private void initView() {

        mTextInCarTv = (TextView) mView.findViewById(R.id.car_entrance_carpool_text);
        mSubHeadTv = (TextView) mView.findViewById(R.id.tv_carpool_subhead_title);

        parentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                APIProxy.navi().navigateTo(CarpoolHomePage.class, null);
            }
        });
    }

    private boolean isFirstUseCarpool() {

        return CarpoolSharedPreferences.isFristUse(APIProxy.res().getBaseActivity());
    }

    public boolean isSupportCarpool() {
        boolean supportCarpool = false;
        if(mainConfigResponse == null){
            return true;
        }
        if(mainConfigResponse.data == null){
            return supportCarpool;
        }
        if(mainConfigResponse.data.citylist == null){
            MainConfigData mainConfigData = new MainConfigData(APIProxy.res().getBaseActivity());
            mainConfigData.setCityCode(UserInfoSetting.getCityId());
            mainConfigData.get(mMainConfigResponseListener);
            return supportCarpool;
        }

        ArrayList<MainConfigResponse.MainConfig.CityItem> citylist = new ArrayList<MainConfigResponse.MainConfig.CityItem>();
        citylist =  mainConfigResponse.data.citylist;
        if(citylist == null){
            return supportCarpool;
        }
        if(citylist.size() == 0){
            return supportCarpool;
        }
        supportCarpool = false;
        for(int i = 0; i < citylist.size(); i++){
            if(citylist.get(i) != null){
                int currentCityId = SafeUtils.safeString2int(UserInfoSetting.getCityId());
                int supportCityId = SafeUtils.safeString2int(citylist.get(i).cityCode);
                if(currentCityId == supportCityId){
                    return true;
                }
            }
        }

        return supportCarpool;
    }

    private CarpoolPosition mHomeInfoLL;
    private CarpoolPosition mCompanyInfoLL;
    private CarpoolPosition mHomeInfoMoc;
    private CarpoolPosition mCompanyInfoMoc;
    private void saveHomeAndCompanyGeo(){

        mHomeInfoMoc = new CarpoolPosition();
        mCompanyInfoMoc = new CarpoolPosition();
        mHomeInfoLL = new CarpoolPosition();
        mCompanyInfoLL = new CarpoolPosition();

        Preferences preferences = Preferences.build(APIProxy.sys().getApplicationContext());
        String companyAddr = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_ADDR, "");
        String companyGeo = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_GEO, "");
        String homeAddr = preferences.getString(CarpoolEntity.SHORTCUT_HOME_ADDR, "");
        String homeGeo = preferences.getString(CarpoolEntity.SHORTCUT_HOME_GEO, "");

        GeoPoint companyGeoPtLL = MapUtils.mc2ll(ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(companyGeo));
        GeoPoint homeGeoPtLL = MapUtils.mc2ll(ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(homeGeo));
        GeoPoint companyGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(companyGeo);
        GeoPoint homeGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(homeGeo);


        mHomeInfoLL.x = homeGeoPtLL.getLongitude();
        mHomeInfoLL.y = homeGeoPtLL.getLatitude();
        mHomeInfoLL.address = homeAddr;
        mCompanyInfoLL.x = companyGeoPtLL.getLongitude();
        mCompanyInfoLL.y = companyGeoPtLL.getLatitude();
        mCompanyInfoLL.address = companyAddr;

        mHomeInfoMoc.x = homeGeoPtMoc.getLongitude();
        mHomeInfoMoc.y = homeGeoPtMoc.getLatitude();
        mHomeInfoMoc.address = homeAddr;
        mCompanyInfoMoc.x = companyGeoPtMoc.getLongitude();
        mCompanyInfoMoc.y = companyGeoPtMoc.getLatitude();
        mCompanyInfoMoc.address = companyAddr;

        if(!"".equals(mHomeInfoMoc.address) && mHomeInfoMoc.x != 0.0 && mHomeInfoMoc.y != 0.0){
            CarpoolSharedPreferences.setHomeGeoAddrInfo(APIProxy.res().getBaseActivity(), mHomeInfoMoc);
        }
        if(!"".equals(mCompanyInfoMoc.address) && mCompanyInfoMoc.x != 0.0 && mCompanyInfoMoc.y != 0.0) {
            CarpoolSharedPreferences.setCompanyGeoAddrInfo(APIProxy.res().getBaseActivity(), mCompanyInfoMoc);
        }
    }

    /**
     * @param count
     */
    protected void setUnFinishOrderCount(int count) {
        StringBuilder sb = new StringBuilder();
        sb.append("您有");
        sb.append("<font color=\"#ff481d\">");
        sb.append(count);
        sb.append("</font>");
        sb.append("笔未完成订单");
        CharSequence cs = Html.fromHtml(sb.toString());
        mTextInCarTv.setText(cs);
    }
}
